import { Component, Prop, Vue } from "vue-property-decorator";
import { AuthServer } from "@/inject/core/auth.ts";
@Component
export default class Auth extends Vue {
    @Prop({
        type: Boolean,
        default: false
    })
    readonly slim!: boolean;

    @Prop({
        type: String,
        default: "span"
    })
    readonly tag!: string;

    /**
     * rules的值可能存在的情况
     * @page1 //代表检测name为page1的页面是否具有权限
     * @page1:add|remove // 检测name为page1的页面是否具有add，remove权限
     * @page1:add.o.p|remove
     * @page1:add.o.p|remove,@page2:add|remove
     * add|remove // 检测当前route页面是否具有add，remove权限
     * add.o.p|remove // 检测当前route页面是否具有add，remove权限
     */
    @Prop({
        type: String,
        default: ""
    })
    readonly rules!: string;

    /**
     * 每一项参考rules的值可能存在的情况
     * 如果传递了rulesOr则会覆盖rules的结果
     * rulesOr的匹配规则和rules一样，只是多项中只要有一项满足则认为具有权限
     */
    @Prop({
        type: Array,
        default: () => {
            return [];
        }
    })
    readonly rulesOr!: any[];

    getRules(rules: string) {
        let _name = this.$route.name || "";
        if (this.$route.meta && this.$route.meta.roleName) {
            _name = this.$route.meta.roleName;
        }
        const _rules: any[] = rules.split(",");
        const _authPayload: any = {};
        _rules.forEach(cur => {
            let _cur = "";
            let _key = "";
            if (/^@(.+):/gi.test(cur) || /^@(.+)/gi.test(cur)) {
                _key = RegExp.$1;
                _cur = cur.replace(/(^@(.+):)|(^@(.+))/gi, "");
            } else {
                _cur = cur;
                _key = _name;
            }
            if (_cur) {
                _authPayload[_key] = _cur.split("|").map(sub => {
                    return sub.split(".");
                });
            } else {
                _authPayload[_key] = [];
            }
        });
        return _authPayload;
    }

    render() {
        const authServer = new AuthServer();
        let _auth = authServer.checkAuth(this.getRules(this.rules));
        if (this.rulesOr.length > 0) {
            for (let i = 0; i < this.rulesOr.length; i++) {
                const curRules = this.rulesOr[i];
                const _curAuth = authServer.checkAuth(this.getRules(curRules));
                if (_curAuth) {
                    _auth = _curAuth;
                    break;
                }
            }
        }
        const _create = this.$createElement;
        const _default: any[] = this.$slots.default || [];
        return _auth
            ? this.slim && _default.length <= 1
                ? _default[0]
                : _create(this.tag, this.$slots.default)
            : null;
    }
}
